package src.other.beogold.u9c.client;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.exception.CacheException;
import com.rkhd.platform.sdk.http.CommonData;
import com.rkhd.platform.sdk.http.CommonHttpClient;
import com.rkhd.platform.sdk.http.HttpResult;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.service.CacheService;
import org.apache.commons.lang.StringUtils;
import src.other.beogold.u9c.utils.SignUtil;

import java.util.Base64;


/**
 * @Description: ipaas 集中平台连接
 * @Author: lys
 * @Date: 2025-07-09 15:30
 */
public class PaasClient {

    // Auth 账号:密码
    private static final String basicAuth = "ASS_NC-SHFQQN34:VZocrT24vpUzrE8e0iEVd00Qh72PTJYv";

    // 账号秘钥
    private static final JSONObject tokenReqData = new JSONObject(){{
        put("account", "ASS_NC-SHFQQN34");
        put("secret", "fd13ac11-568a-41da-93c4-b442652da51e");
    }};

    private static final Logger logger = LoggerFactory.getLogger();

    private static final CacheService cacheService = CacheService.instance();

    private static final String TOKEN_KEY = "IPAAS_SERVICE_TOKEN";

    public static final String BASE_URL = "https://apidev.angelgroup.com.cn:10008"; // 访问域名

    public static final String GET_TOKEN = BASE_URL + "/api/ipaas/getToken"; // 获取token

    public static final String PUSH_SERVICE_REQUEST = BASE_URL + "/api/ASO/pushServiceRequest"; // 推送服务请求

    public static final String URGE_WORK_ORDER = BASE_URL + "/api/ASO/urgeWorkOrder"; // 催单

    public static final String PUSH_ORDER = BASE_URL + "/api/ASO/createOrUpdateCommercialFilterOrder"; // 新增、修改订单

    public static final String PUSH_ORDER_DETAIL = BASE_URL + "/api/ASO/getCommercialFilterOrderDetil"; // 新增、修改订单明细

    public static final String PUSH_RETURN_ORDER = BASE_URL + "/api/ASO/manageCommercialFilterOrderReturn"; // 新增、修改退货订单

    public static final String PUSH_RETURN_ORDER_DETAIL = BASE_URL + "/api/ASO/manageCommercialFilterOrderReturnDetil"; // 新增、修改退货订单明细

    public static void main(String[] args) throws Exception {
        //getToken();
    }

    /**
     * 发送 post 请求
     * @param reqUrl
     * @param reqData
     * @return
     * @throws Exception
     */
    public static JSONObject post(String reqUrl, Object reqData) throws CacheException {
        String signUrl = SignUtil.signUrl(reqUrl);
        logger.info("reqData = "+ reqData);
        logger.info("signUrl = "+ signUrl);

        // 根据请求获取参数
        CommonData build = CommonData.newBuilder().callString(signUrl)
                .callType("POST")
                .header("JWT", getToken())
                .body(reqData.toString())
                .build();
        HttpResult execute = CommonHttpClient.instance(1000 * 35, 1000 * 35).execute(build);
        JSONObject response = JSONObject.parseObject(execute.getResult());
        logger.info("response = "+ response);

        // 判断token是否过期 { "exp": "token expired" }
        String exp = response.getString("exp");
        if (exp != null && exp.indexOf("expired") != -1) {
            logger.error("IPAAS token过期，重新发起请求");
            cacheService.delete(TOKEN_KEY);
            return post(reqUrl, reqData);
        }

        // 判断是否
        //Integer code = response.getInteger("ErrorCode");
        //if (code != 0) {
        //    String msg = response.getString("Message");
        //    logger.error("请求异常: " + msg);
        //    return null;
        //}

        return response;
    }

    /**
     * 获取 token
     * @return
     */
    public static String getToken() throws CacheException {
        // 本地测试
        //if (true) {
        //    return "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOm51bGwsIm5iZiI6MTc1ODI0NDYyOCwiaXNzIjoiQVNTX05DLVNIRlFRTjM0IiwiZXhwIjoxNzU4MjUxODI4LCJpYXQiOjE3NTgyNDQ2Mjh9.k5TnuRKpddf5wtkCAbynRb0I4csSkvUVeF8hRZSt3Pk";
        //}
        // 判断缓存中是否存在
        String token = cacheService.get(TOKEN_KEY);
        if (StringUtils.isNotBlank(token)) {
            logger.info("IPAAS获取缓存token");
            return token;
        }

        // Basic Auth
        String encodedString = Base64.getEncoder().encodeToString(basicAuth.getBytes());
        CommonData build = CommonData.newBuilder().callString(GET_TOKEN)
                .callType("POST")
                .header("Authorization", "Basic " + encodedString)
                .body(tokenReqData.toJSONString())
                .build();
        HttpResult execute = CommonHttpClient.instance().execute(build);
        JSONObject response = JSONObject.parseObject(execute.getResult());
        logger.info("result = " + response);
        Integer code = response.getInteger("code");
        if (code != 200) {
            String msg = response.getString("msg");
            throw new RuntimeException("获取token异常:" + msg);
        }

        token = response.getJSONObject("data").getString("token");
        cacheService.set(TOKEN_KEY, token);
        return token;
    }

    public static JSONObject packOjb(Object data) {
        if (data == null)  return null;
        return new JSONObject().fluentPut("value", data);
    }

    public static JSONObject packOjb(String logicalname, String key, String value) {
        if (StringUtils.isBlank(value)) return null;

        JSONObject obj = new JSONObject();
        obj.put("logicalname", logicalname);
        obj.put("keyattributes", new JSONObject().fluentPut(key, value));
        return obj;
    }

}
